import { Component } from 'react';

import {Switch, TextareaField, Toast, Button , Group, Context, Card, Field, Boxs, Dialog} from 'saltui';
const { Box, HBox,VBox } = Boxs;
import SelectMember from 'components/selectMember';
import { msgNoData } from '../../../app/variables';
import DB from '../../../app/db';

import './PageHome.less';
import Upload from 'components/upload';
const {
	Count
} = TextareaField;
export default class PageHome extends Component {


 constructor(props) {
    super(props);
    let meetingId = this.props.params.id;
    if (meetingId == null || meetingId == '' || meetingId == undefined || meetingId == 'undefined') {
      meetingId = '';
    }

    let editType = '1';
    let memoId = this.props.params.memoId;
    if (memoId == null || memoId == '' || memoId == undefined || memoId == 'undefined' || memoId=="add") {
      memoId = '';
      editType = '0';
    }

    let type = this.props.params.type;
    if (type == 'edit') {
      editType = '0';
    }
    let message = this.props.params.message;
    //关闭加载页的遮罩效果
    $(".loading-containter").hide();
    //禁用ios弹性事件
    dd.ui.webViewBounce.disable();
    var thirdMenuType = getLoginUserInfo().thirdMenuType;
    this.state = {
      thirdMenuType:thirdMenuType,
      editType:editType,
      meetingId:meetingId,
      memoId:memoId,
      name:'',
      meetingTime:'',
      startTime: '',
      endTime: '',
      meetingRoom:'',
      meetingAddress: '',

      absent:'',
      see:'',

      type:type,
      hoster:'',
      memoer:'',
      joiners:[],
      absenter:[],

      memoScope:'',
      jsonStrMemoUser:'',

      fileId:'',
      attIdJson:[],

      meetingContent:'',
      meetingAgenda:'',
      meetingTasks:'',

      picArray:[],
      isMessage:message,
      isDeleted:false,

      isCreatedBy:false,
      isEmceeUser:false,
      isMemoUser:false,

      switchShow:false,//控制水印开关是否显示
      watermarkContent:'',
      showWatermark:false,//是否启用水印
    };
    
    let t = this;
    let userId = document.getElementById("userHiddenId").value;
    var isHelpNew = 1;
    dd.util.domainStorage.getItem({ //帮助按钮
       name:'meeting_helpNew_'+userId , // 存储信息的key值
       onSuccess : function(info) {
            var helpNew = info.value;
            if( typeof(helpNew) == 'undefined' || helpNew == '' ){
              isHelpNew = 2;
            }
            //初始化按钮
            t.initButton(isHelpNew);
       },
       onFail : function(err) {
            //alert(JSON.stringify(err));
       }
    });
  }

  //初始化按钮
  initButton(isHelpNew){
    //设置帮助
    /*dd.biz.navigation.setIcon({
        showIcon : true,//是否显示icon
        iconIndex : isHelpNew,//显示的iconIndex,如上图
        onSuccess : function(result) {
            location.hash='help/help_index';
        },
        onFail : function(err) {
        //jsapi调用失败将会回调此函数
        }
    });*/
  }

  componentDidMount(){
    $(window).scrollTop(0);//页面回滚回顶端
    let emiTitle = '添加会议纪要';
    let isViewType = '0';
    if(this.state.editType =='1'){
      emiTitle = '查看会议纪要';
      isViewType = '1';
    }else if(this.state.type =='edit'){
      emiTitle = '编辑会议纪要';
    }
    $("title").text(emiTitle);
    var thirdMenuType = getLoginUserInfo().thirdMenuType;
    if(thirdMenuType == 'DING'){
      dd.biz.navigation.setTitle({
        title : emiTitle,//控制标题文本，空字符串表示显示默认文本
        onSuccess : function(result) {},
        onFail : function(err) {}
      });
    }else if(thirdMenuType =='MH'){
      !!emp&&emp.window.setTitle({
        title: {
            text: emiTitle,
            icon: '',
            actionmenu: {}
        },
      });
    }

      let t = this;
      let memoId = this.state.memoId;
      let meetingId = this.state.meetingId;
      DB.SomeModuleAPI.editMemoInfo({id:memoId,applyRecordId:meetingId,isViewType:isViewType})
            .then((content) => {
          let isDeleted = content.isDeleted;
          if(t.state.isMessage == 'message' && isDeleted){
            t.setState({
              isDeleted:isDeleted
            })
            return false;
          }
          let apply = content.applyRecord;

          let meetingRoom = '', meetingAddress = '';
          if (content.boardroomSet != null) {
            meetingRoom = content.boardroomSet.name;
            meetingAddress = content.boardroomSet.address;
          }
          /*var meetingTime = apply.startTime;
          var endTime = apply.endTime.split(" ")[1];
          meetingTime += " ~ "+endTime;*/
          var meetingContent = "";
          var _memoScope = "";
          if (content.memoInfo != null) {
            if(content.memoInfo.content != null) meetingContent = content.memoInfo.content;
            _memoScope = content.memoInfo.memoUser;
          }
          var _fileId = "";
          if(content.fileIds != "")_fileId = content.fileIds;
          var _attIdJson=[];
          if(content.attIdJson != null) _attIdJson=content.attIdJson;

          let switchShow = false;
          let showWatermark = false;
          if(content.watermark == '1') switchShow = true;
          if(content.memoInfo.showWatermark != null && content.memoInfo.showWatermark != '')
            showWatermark = content.memoInfo.showWatermark == '1' ? true : false;

          t.setState({
            startTime: apply.startTime,
            endTime: apply.endTime,
            meetingRoom:meetingRoom,
            meetingAddress: meetingAddress,
            address:apply.address,
            memoScope:_memoScope,
            hoster:apply.emceeUser,
            memoer:apply.memoUser,
            joiners:content.attendUserName,
            absenter:content.noAttendUserName,
            fileId:_fileId,
            attIdJson:_attIdJson,
            name:apply.name,
            absent:content.noAttendUserName,
            meetingContent:meetingContent,
            meetingAgenda:content.memoInfo.agenda?content.memoInfo.agenda:'',
            meetingTasks:content.memoInfo.tasks?content.memoInfo.tasks:'',
            isCreatedBy:content.isCreatedBy,
            isEmceeUser:content.isEmceeUser,
            isMemoUser:content.isMemoUser,
            switchShow:switchShow,
            watermarkContent:content.watermarkContent,//水印内容
            showWatermark:showWatermark
          }, function(){
            if(t.state.isCreatedBy || t.state.isEmceeUser || t.state.isMemoUser)
              t.refs.selectMember_memoUserScope.initSelectData();
            t.refs.selectMember_emceeUser.initSelectData();
            t.refs.selectMember_memoUser.initSelectData();
            t.refs.selectMember_attendUser.initSelectData();
            t.refs.selectMember_noneAttendUser.initSelectData();
            t.refs.upload.initData();
            if(t.state.editType == '1' && t.state.switchShow && t.state.showWatermark){//查看模式下有水印
              let watermarkContent = t.state.watermarkContent;
              try{
                if(watermarkContent != null && typeof loginUserInfo != 'undefined' && loginUserInfo != ''){
                  showWaterMarker('waterMarker', watermarkContent);
                }
              }catch(e){ 
              } 
            }
          });
        }).catch((error) => {
        });
  }

  onChange(val) {
    this.setState({
      value: val,
    });
  }

  handleTextChange(name, newValue, size) {
    if (newValue.length <= size) {
      this.setState({
        [name]: newValue,
      });
    }
  }

  // 添加会议纪要
  save(){
    let t = this;

    if (this.state.meetingContent==null || this.state.meetingContent.trim()=='') {
      Toast.show({
              type: 'error',
              content: '请填写纪要内容',
              onHide: function () {
              }
          });
      return;
    }
    if(this.state.meetingContent != null && isEmojiCharacter(this.state.meetingContent)){
      Toast.show({
        type: 'error',
        content: '纪要内容不支持表情输入',
        onHide: function () {}
      });
      return;
    }
    let _jsonStrMemoUser = "";
    if (t.state.jsonStrMemoUser!="" && t.state.jsonStrMemoUser!=null && t.state.jsonStrMemoUser!=undefined) {
      _jsonStrMemoUser = JSON.stringify(t.state.jsonStrMemoUser);
    }
    let _showWatermark = t.state.showWatermark ? '1' : '0';
    let param = {
      applyRecordId:t.state.meetingId,
      id:t.state.memoId,
      content:t.state.meetingContent,
      tasks:t.state.meetingTasks,
      agenda:t.state.meetingAgenda,
      fileId:t.state.fileId,
      jsonStrMemoUser:_jsonStrMemoUser,
      showWatermark:_showWatermark
    }
    DB.SomeModuleAPI.saveMemoInfo({message: JSON.stringify(param)})
        .then((content) => {
          Toast.show({
          type: 'success',
              content: '保存成功'
           });

          //返回至列表页面
          setTimeout(function(){
            history.back();
          },2000);
        }).catch((error) => {
          
            if(typeof(error.errorMsg) == 'undefined'){
              Toast.show({
              type: 'error',
              content: '保存出错'
               });
            }else{
              Toast.show({
              type: 'error',
              content: error.errorMsg
               });
            }
        });  
  }

  transmitMemo(){
    location.hash = 'meeting/memoTransmit/' + this.state.memoId;
  }

  delete(){
    let t = this;
    Dialog.confirm({
      title: '提示',
      locale: 'zh_CN',
      content: '确定要删除当前会议纪要吗？',
      onConfirm() {
        DB.SomeModuleAPI.deleteMemoInfo({memoId:t.state.memoId}).then((content) => {
          Toast.show({
            type: 'success',
            content: '删除成功'
          })
          //返回至列表页面
          setTimeout(function(){
            history.back();
          },2000);
        }).catch((error) => {
            if(typeof(error.errorMsg) == 'undefined'){
              Toast.show({
                type: 'error',
                content: '删除出错'
              });
            }else{
              Toast.show({
                type: 'error',
                content: error.errorMsg
              });
            }
        }); 
      },
      onCancel() {
        return;
      },
    });

  }

  //获取联系人
  changeSelectMember(newValue){
      this.setState({
        jsonStrMemoUser: newValue
      });
  }

  changePic(imgid){
    var _fileId = "";
    imgid.map(function(item,index){
      _fileId += item.id+"|";
    });
    if(_fileId.length>1){
      _fileId = _fileId.substring(0,_fileId.length-1);
    }
    this.setState({
      attIdJson:imgid,
      fileId:_fileId
    });
  }

  handleChange(field, value) {
    this.setState({
      [field]: value,
    });
  }

  render() {
    const t = this;
    let isDeleted = t.state.isDeleted;
    if(!isDeleted){
      const headerCls = Context.prefixClass('card-header');
      const isReadOnly = true;

      var meetingAddress = ""
      if(this.state.boardroomId!="" && this.state.meetingRoom != ""){
        meetingAddress = this.state.meetingRoom+"（"+this.state.meetingAddress+"）";
      }else{
        meetingAddress = this.state.address;
      }

      return (
        <div className="meeting-details t-PB68" id="waterMarker">
          <div className="card-wrap">
            <Card className="card-sence">
              <div className={headerCls} style={{margin:'0'}}>
                <span className="card-username">{t.state.name}</span>            
              </div>
              <div className="t-PL16 t-PR16 t-PT10 t-PB10">
                <HBox>
                  <Box><i className="iconfont icon-time t-FCc t-MR4 t-LH1_6" style={{fontSize:14}}></i></Box>
                  <Box className="card-desc">开始时间：</Box>
                  <Box flex={1} className="card-desc">{t.state.startTime}</Box>
                </HBox>
                <HBox>
                  <Box><i className="iconfont icon-time t-FCc t-MR4 t-LH1_6" style={{fontSize:14}}></i></Box>
                  <Box className="card-desc">结束时间：</Box>
                  <Box flex={1} className="card-desc">{t.state.endTime}</Box>
                </HBox>
                <HBox>
                  <Box><i className="iconfont icon-place t-FCc t-MR4 t-LH1_6" style={{fontSize:14}}></i></Box>
                  <Box className="card-desc">会议地址：</Box>
                  <Box flex={1} className="card-desc">{meetingAddress == "" ? "无" : meetingAddress}</Box>
                </HBox>
              </div>
            </Card>            
            <div className="t-BCf7 t-H10"></div>
            <div className={t.state.editType=='0'?'':'t-DN'}>
              <Group.List >
                <TextareaField label="纪要内容" minRows={3} maxRows={10} required={true}
                  placeholder="请输入纪要内容" value={t.state.meetingContent} layout="v"
                  onChange={(value) => { t.handleTextChange('meetingContent', value, 1000); }}>
                  <Count total={1000} length={t.state.meetingContent.length} /></TextareaField>
              </Group.List>
            </div>
            <Group.List className={t.state.editType=='1'?'':'t-DN'}>
               <TextareaField label="纪要内容" minRows={3} maxRows={10} required={true} readOnly={true}
                  placeholder="请输入纪要内容" value={t.state.meetingContent} layout="v" />
            </Group.List>

            <Group.List  className={t.state.editType=='0'?'':'t-DN'}>
              <TextareaField label="会议议程" minRows={3} maxRows={10} required={false}
                placeholder="请输入会议议程" value={t.state.meetingAgenda} layout="v"
                onChange={(value) => { t.handleTextChange('meetingAgenda', value, 1000); }}>
                <Count total={1000} length={t.state.meetingAgenda.length} /></TextareaField>
            </Group.List>
            <Group.List className={t.state.editType=='1'?'':'t-DN'}>
               <TextareaField label="会议议程" minRows={3} maxRows={10} required={false} readOnly={true}
                  placeholder="请输入会议议程" value={t.state.meetingAgenda} layout="v" />
            </Group.List>

            <Group.List  className={t.state.editType=='0'?'':'t-DN'}>
              <TextareaField label="需落实任务" minRows={3} maxRows={10} required={false}
                placeholder="请输入需落实任务" value={t.state.meetingTasks} layout="v"
                onChange={(value) => { t.handleTextChange('meetingTasks', value, 1000); }}>
                <Count total={1000} length={t.state.meetingTasks.length} /></TextareaField>
            </Group.List>
            <Group.List className={t.state.editType=='1'?'':'t-DN'}>
               <TextareaField label="需落实任务" minRows={3} maxRows={10} required={false} readOnly={true}
                  placeholder="请输入需落实任务" value={t.state.meetingTasks} layout="v" />
            </Group.List>

            <div className="t-BCf7 t-H10"></div> 
            {t.state.editType=='1' ?
              t.state.thirdMenuType == "MH" ?
                <Group.List>
                <Upload 
                  label="附件"
                  initList={t.state.attIdJson} 
                  dir="meeting" 
                  canAdd={false}
                  canDel={false}
                  ref="upload"/>
                </Group.List>
                :
                <Group.List>
                <Upload 
                  uploadType="file"
                  label="附件"
                  initList={t.state.attIdJson} 
                  dir="meeting" 
                  canAdd={false}
                  canDel={false}
                  ref="upload"/>
                </Group.List>
              :
              t.state.thirdMenuType == "MH" ?
                <Group.List className="t-PB16">
                <Upload 
                  label="附件"
                  initList={t.state.attIdJson} 
                  dir="meeting" 
                  canAdd={true}
                  canDel={true}
                  limitNo="9"
                  onChange={this.changePic.bind(this)}
                  onDel={this.changePic.bind(this)}
                  ref="upload"/>
                </Group.List>
                :
                <Group.List className="t-PB16">
                <Upload 
                  uploadType="file"
                  label="附件"
                  initList={t.state.attIdJson} 
                  dir="meeting" 
                  canAdd={true}
                  canDel={true}
                  limitNo="9"
                  onChange={this.changePic.bind(this)}
                  onDel={this.changePic.bind(this)}
                  ref="upload"/>
                </Group.List>
            }
            
            {t.state.isCreatedBy || t.state.isEmceeUser || t.state.isMemoUser ? t.state.editType=='1'?  
              <Group.List>
                <SelectMember
                  required={false}
                  readOnly={true}
                  label="查看范围"
                  placeholder="请选择查看范围"
                  code="user,org,station,group"
                  checkType="checkbox"
                  fieldDataValue={t.state.memoScope}
                  scopeTable="oa_meeting_apply_record_scope"
                  fieldTable="oa_meeting_memo_info"
                  fieldData="memo_scope"
                  ref="selectMember_memoUserScope"
                  isDelete={false}
                  showType="list"
                  includeDel="1"
                />
              </Group.List>
            : 
              <Group.List>
                <SelectMember
                  required={false}
                  readOnly={false}
                  label="查看范围"
                  placeholder="请选择查看范围"
                  code="user,org,station,group"
                  checkType="checkbox"
                  fieldDataValue={t.state.memoScope}
                  scopeTable="oa_meeting_apply_record_scope"
                  fieldTable="oa_meeting_memo_info"
                  fieldData="memo_scope"
                  ref="selectMember_memoUserScope"
                  isDelete={true}
                  showType="list"
                  onChange={this.changeSelectMember.bind(this)}
                />
              </Group.List> : ""}
            {this.state.editType == '0' && this.state.switchShow ? 
              <Group.List>
                <div className="dd-item">
                  <label className="label-txt">显示水印</label>
                  <Switch on={this.state.showWatermark} onChange={this.handleChange.bind(this, 'showWatermark')} />
                </div>
              </Group.List> : ""
            }
            
            <Group.List>
              <SelectMember
                required={false}
                readOnly={true}
                label="主持人"
                placeholder="请选择主持人"
                code="user"
                checkType="radio"
                fieldDataValue={t.state.hoster}
                scopeTable="oa_meeting_apply_record_scope"
                fieldTable="oa_meeting_apply_record"
                fieldData="emcee_user"
                ref="selectMember_emceeUser"
                isDelete={false}
                showType="list"
                includeDel="1"
              />
            </Group.List>
            <Group.List>
              <SelectMember
                required={false}
                readOnly={true}
                label="记录人"
                placeholder="请选择记录人"
                code="user"
                checkType="radio"
                fieldDataValue={t.state.memoer}
                scopeTable="oa_meeting_apply_record_scope"
                fieldTable="oa_meeting_apply_record"
                fieldData="memo_user"
                ref="selectMember_memoUser"
                isDelete={false}
                showType="list"
                includeDel="1"
              />
            </Group.List>
            <Group.List>
              <SelectMember
                required={false}
                readOnly={true}
                label="参会人员"
                placeholder="请选择参会人员"
                code="user,org"
                checkType="checkbox"
                defaultValue={t.state.joiners}
                ref="selectMember_attendUser"
                isDelete={false}
                showType="list"
                includeDel="1"
              />
            </Group.List>
            <Group.List>
              <SelectMember
                required={false}
                readOnly={true}
                label="缺席人员"
                placeholder="请选择缺席人员"
                code="user,org"
                checkType="checkbox"
                defaultValue={t.state.absenter}
                ref="selectMember_noneAttendUser"
                isDelete={false}
                showType="list"
                includeDel="1"
              />
            </Group.List>
          </div> 
          {t.state.editType=='0' ?
            <div><Button type="primary" onClick={this.save.bind(this)}>保存</Button></div>
            :
            <div>
              <Button.Group >
                <Button type="primary" display="inline" onClick={this.transmitMemo.bind(this)}>转发</Button>
                <Button className={t.state.type != 'viewList' && (t.state.isCreatedBy || t.state.isEmceeUser || t.state.isMemoUser) ? '' : 't-DN'} type="secondary" display="inline" onClick={this.delete.bind(this)}>删除</Button>                
              </Button.Group>
            </div> 
          }

        </div>)
    }else{
      return (
        <div className="dd-state-page">
          <div className="dd-state-box">
            <VBox hAlign="center">
              <Box>
                <div>
                  <img src={msgNoData} alt="" />
                </div>
              </Box>
              <Box className="t-FS14 t-MT30 t-FAC t-LH1_3 t-FCddfontblue-40">
                内容已删除
              </Box>
            </VBox>
          </div>
        </div>
      )
    }
  }
}


